/* eslint-disable no-unused-vars */
import React, { useEffect, useState } from "react";
import './launchmode2.css';
import { useHistory } from "react-router-dom/cjs/react-router-dom";
import { useDispatch, useSelector } from "react-redux";

import icon_app_logo from "@/assets/icon_app_logo.png"

import { saveEvent } from "@/store/actions/saveEvent";
import { LangStore } from "@/utils/langStore";

import { LangEnGhs } from "@/utils/langEnGhs";
import { LangEnKes } from "@/utils/langEnKes";
import { LangEnUgx } from "@/utils/langEnUgx";
import { LangFrFcfa } from "@/utils/langFrFcfa";
import { LangFrXaf } from "@/utils/langFrXaf";
import { getZone } from "@/store/actions/zone";
import { getAreaInfo, setAreaInfo } from "@/utils/storage";
// import { el, tr } from "date-fns/locale";
import { useFormik } from "formik";
import { DotLoading, Mask } from "antd-mobile";
import { doLogin, getOtp } from "@/store/actions/login";

let timeId

/**
 * 落地页-1
 */
export default function LaunchMode2() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    // 获取路由历史 history 对象
    const history = useHistory()

    // 文案翻译
    const [curLang, setCurLang] = useState(null);

    // 接口转发
    const [curPath, setCurPath] = useState(null);

    // 当前天数
    const [isShortTerm, setIsShortTerm] = useState(true);

    // 当前发送验证码按键文本
    const [curOtpText, setCurOtpText] = useState("");

    // 当前发送验证码按键文本
    const [isOtpCutdown, setIsOtpCutdown] = useState(false);

    //获取 Redux 分发器
    const dispatch = useDispatch()

    //启动时请求用户状态
    useEffect(() => {
        //添加 fb 像素
        // eslint-disable-next-line no-undef
        fbq('track', 'Page_LAUNCH');
        // eslint-disable-next-line no-undef
        gtag('track', 'Page_LAUNCH');

        // 查询缓存是否存在
        let areaInfo = getAreaInfo();
        if (areaInfo.length > 0) {
            // 直接返回
            onDoGetZoneCallback(true, areaInfo);
        } else {
            // 请求时区转发
            doGetZone();
        }

        return () => {
            if (curPath && curPath.length > 0) {
                //打点
                doHitEvent(curPath, "sign_launchmode2_END");
            } else {
                // 查询缓存是否存在
                let areaInfo = getAreaInfo();
                if (areaInfo.length > 0) {
                    //打点
                    doHitEvent(areaInfo, "sign_launchmode2_END");
                }
            }

            timeId && clearInterval(timeId);
        }
    }, []);

    // Formik 表单对象
    const form = useFormik({
        //设置表单初始值
        initialValues: {
            mobile: '',
            code: ''
        },

        //提交
        onSubmit: values => {
            console.log(values)

            //提交登录
            onLoginSubmit()
        },

        //校验
        validate(values) {
            const errors = {}
            if (!values.mobile) {
                errors.mobile = curLang.enterPhoneErr;
            }
            if (!values.code) {
                errors.code = curLang.enterOtpErr;
            }

            return errors
        }
    });

    //点击登录
    const onLoginSubmit = async () => {
        if (curPath && (curPath.length > 0)) {
            try {
                //打点
                doHitEvent(curPath, "sign_LOGIN_COMMIT_CLICK");

                //验证手机号
                let mobile = form.values.mobile + "";

                //验证验证码
                let code = form.values.code + "";

                //请求登录
                doOtpLogin(mobile, code);

            } catch (e) {
                console.log(e)
            }
        }
    };

    //点击获取otp
    const onHandleSendCode = async () => {
        //验证是否在倒计时中
        console.log("onHandleSendCode:" + curPath + "," + form.values.mobile + "," + curOtpText + "," + curLang.getOtp);
        const mobile = form.values.mobile + "";
        let con1 = curPath && (curPath.length > 0);
        let con2 = (mobile > 0);
        let con3 = (curOtpText === curLang.getOtp);
        if (con1 && con2 && con3) {
            //打点
            doHitEvent(curPath, "sign_LOGIN_OTP_CLICK");

            //验证手机号
            if (mobile.length < 9) {
                form.setTouched({ mobile: true })
                return
            }

            //请求发送短信
            doSendOtp(mobile)
        } else {
            console.log("=======")
        }
    };


    //请求短信接口
    const doSendOtp = async (mobile) => {
        if (curPath && (curPath.length > 0) && mobile && (mobile.length > 0)) {
            console.log("doSendOtp: " + mobile);
            try {
                //显示loading
                setMaskVisible(true)

                //获取Action -- 暂时关闭
                const action = getOtp(curPath, mobile, onGetOtpCallback);

                //触发接口
                await dispatch(action)

            } catch (e) {
                console.log(e)
            }
        }
    };

    //请求登录接口
    const doOtpLogin = async (mobile, code) => {
        console.log("doOtpLogin:" + curPath + "," + mobile + "," + code);
        if (curPath && (curPath.length > 0) && mobile && (mobile.length > 0) && code && (code.length > 0)) {
            try {
                //显示loading
                setMaskVisible(true)

                //获取Action
                const action = doLogin(curPath, mobile, code, onDoLoginCallback);

                //触发接口
                await dispatch(action)

            } catch (e) {
                console.log(e)
            }
        }
    }


    //请求转发接口
    const doGetZone = async () => {
        console.log("doGetZone: ");

        try {
            //显示loading
            // setMaskVisible(true)

            //获取Action
            const action = getZone(onDoGetZoneCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    };

    // 请求otp接口 返回
    const onGetOtpCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('请求otp接口 返回: ' + success);

        timeId && clearInterval(timeId);

        if (success) {
            // 开始倒计时
            let curSec = 10
            timeId = setInterval(() => {
                curSec -= 1;
                if (curSec === 0) {
                    setCurOtpText(curLang.getOtp);
                    setIsOtpCutdown(false);
                    timeId && clearInterval(timeId);
                } else {
                    setCurOtpText(curSec + "s");
                    setIsOtpCutdown(true);
                }
            }, 1000);
        }
    };

    // 请求登录接口 返回
    const onDoLoginCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('请求登录接口 返回: ' + success);
        if (success) {
            // 跳转新页页
            window.open(data.regUrl, "_blank");
        }
    };


    // 请求转发接口 返回
    const onDoGetZoneCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('请求转发接口 返回: ' + success);

        if (success && data) {
            setCurPath(data);
            setAreaInfo(data);

            // 判断是否个国家
            if (data.endsWith('gha')) {
                // 加纳
                setCurLang(LangEnGhs);
                setCurOtpText(LangEnGhs.getOtp);

            } else if (data.endsWith('ksh')) {
                // 肯尼亚
                setCurLang(LangEnKes);
                setCurOtpText(LangEnKes.getOtp);

            } else if (data.endsWith('ugx')) {
                // 乌干达
                setCurLang(LangEnUgx);
                setCurOtpText(LangEnUgx.getOtp);

            } else if (data.endsWith('xaf')) {
                // 喀唛隆
                setCurLang(LangFrXaf);
                setCurOtpText(LangFrXaf.getOtp);

            } else {
                // 科特
                setCurLang(LangFrFcfa);
                setCurOtpText(LangFrFcfa.getOtp);
            }

            //打点
            doHitEvent(data, "sign_launchmode2_START")
        }
    };

    // 点击短期天数
    const onHandleSwitchToShortTerm = () => {
        setIsShortTerm(true)
    };

    // 点击长期天数
    const onHandleSwitchToLongTerm = () => {
        setIsShortTerm(false)
    };

    //打点接口
    const doHitEvent = async (path, type, remark = "") => {
        console.log("doHitEvent: " + path + " , " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(path, type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    };

    return (
        <div className="launchmode2Root">
            {/* <NavigateBar theme="transparent" onAddFavorite={() => { }} onAddHome={() => { }}></NavigateBar> */}

            {/* 拿到地区数据时才刷新 */}
            {curLang && <div className="launchmode2Root">
                {/* app 图标 */}
                <div className="launchmode2RowGlobalPadding launchmode2MarginTop25Px">
                    <img className="launchmode2AppLogo" src={icon_app_logo} alt="" />

                    <div className="launchmode2ColumnFullRight launchmode2PaddingLeft16Px">
                        <div className="launchmode2AppName">{curLang.appName}</div>
                    </div>
                </div>

                {/* loan amount */}
                <div className="launchmode2RowGlobalPadding launchmode2MarginTop25Px">
                    <div className="launchmode2LoanAmountBg">
                        <div className="launchmode2LoanAmountTitle">{curLang.loanAmount}</div>
                        {isShortTerm && <div className="launchmode2LoanAmountValue">{curLang.disburseAmountValue60}</div>}
                        {!isShortTerm && <div className="launchmode2LoanAmountValue">{curLang.disburseAmountValue90}</div>}
                    </div>
                </div>

                {/* Loan term */}
                <div className="launchmode2RowGlobalPadding launchmode2MarginTop25Px">
                    <div className="launchmode2LoanTermDot"></div>
                    <div className="launchmode2LoanTerm">{curLang.loanTerm}</div>
                </div>

                {/* 天数切换 */}
                <div className="launchmode2RowGlobalPadding">
                    {isShortTerm && <div className="launchmode2LoanTermSwitchBg">
                        <div className="launchmode2LoanTermSwitchOn">{curLang.days60}</div>
                        <div className="launchmode2LoanTermSwitchOff" onClick={onHandleSwitchToLongTerm}>{curLang.days90}</div>
                    </div>}
                    {!isShortTerm && <div className="launchmode2LoanTermSwitchBg">
                        <div className="launchmode2LoanTermSwitchOff" onClick={onHandleSwitchToShortTerm}>{curLang.days60}</div>
                        <div className="launchmode2LoanTermSwitchOn">{curLang.days90}</div>
                    </div>}
                </div>

                {/* 贷款信息切换 */}
                <div className="launchmode2RowGlobalPadding">
                    {isShortTerm && <div className="launchmode2LoanDetailBg">
                        <div className="launchmode2LoanDetailRow">
                            <div className="launchmode2LoanDetailRowTitle">{curLang.disburseAmount}</div>
                            <div className="launchmode2LoanDetailRowValue">{curLang.disburseAmountValue60}</div>
                        </div>
                        <div className="launchmode2LoanDetailRow launchmode2MarginTop14Px">
                            <div className="launchmode2LoanDetailRowTitle">{curLang.serviceFee}</div>
                            <div className="launchmode2LoanDetailRowValue">{curLang.serviceFeeValue60}</div>
                        </div>
                        <div className="launchmode2LoanDetailRow launchmode2MarginTop14Px">
                            <div className="launchmode2LoanDetailRowTitle">{curLang.interestCharge}</div>
                            <div className="launchmode2LoanDetailRowValue">{curLang.interestChargeValue60}</div>
                        </div>
                        <div className="launchmode2LoanDetailRow launchmode2MarginTop14Px">
                            <div className="launchmode2LoanDetailRowTitle">{curLang.annualPercentageRateAPR}</div>
                            <div className="launchmode2LoanDetailRowValue">{curLang.annualPercentageRateAPRValue60}</div>
                        </div>
                        <div className="launchmode2LoanDetailRow launchmode2MarginTop14Px">
                            <div className="launchmode2LoanDetailRowTitle">{curLang.repayAmount}</div>
                            <div className="launchmode2LoanDetailRowValue">{curLang.repayAmountValue60}</div>
                        </div>
                    </div>}

                    {!isShortTerm && <div className="launchmode2LoanDetailBg">
                        <div className="launchmode2LoanDetailRow">
                            <div className="launchmode2LoanDetailRowTitle">{curLang.disburseAmount}</div>
                            <div className="launchmode2LoanDetailRowValue">{curLang.disburseAmountValue90}</div>
                        </div>
                        <div className="launchmode2LoanDetailRow launchmode2MarginTop14Px">
                            <div className="launchmode2LoanDetailRowTitle">{curLang.serviceFee}</div>
                            <div className="launchmode2LoanDetailRowValue">{curLang.serviceFeeValue90}</div>
                        </div>
                        <div className="launchmode2LoanDetailRow launchmode2MarginTop14Px">
                            <div className="launchmode2LoanDetailRowTitle">{curLang.interestCharge}</div>
                            <div className="launchmode2LoanDetailRowValue">{curLang.interestChargeValue90}</div>
                        </div>
                        <div className="launchmode2LoanDetailRow launchmode2MarginTop14Px">
                            <div className="launchmode2LoanDetailRowTitle">{curLang.annualPercentageRateAPR}</div>
                            <div className="launchmode2LoanDetailRowValue">{curLang.annualPercentageRateAPRValue90}</div>
                        </div>
                        <div className="launchmode2LoanDetailRow launchmode2MarginTop14Px">
                            <div className="launchmode2LoanDetailRowTitle">{curLang.repayAmount}</div>
                            <div className="launchmode2LoanDetailRowValue">{curLang.repayAmountValue90}</div>
                        </div>
                    </div>}
                </div>

                {/* Sign up to apply */}
                <div className="launchmode2RowGlobalPadding launchmode2MarginTop25Px">
                    <div className="launchmode2LoanTermDot"></div>
                    <div className="launchmode2LoanTerm">{curLang.signUpToApply}</div>
                </div>

                <div className="launchmode2RowGlobalPadding launchmode2MarginTop14Px">
                    <form className="pageContentColumn loginAdPaddingHor14Px" onSubmit={form.handleSubmit}>
                        {/* phone number */}
                        <div className="pageContentColumn">
                            <div className="launchmode2InputTitle">{curLang.phoneNumber}</div>
                            <input
                                className="launchmode2Input launchmode2MarginTop10Px"
                                name="mobile"
                                placeholder={curLang.enter}
                                type="number"
                                value={form.values.mobile}
                                onBlur={form.handleBlur}
                                onChange={form.handleChange}
                                autoComplete="off" />
                            {form.errors.mobile && form.touched.mobile && (
                                <div className="launchmode2Validate">{form.errors.mobile}</div>
                            )}
                        </div>

                        {/* OTP */}
                        <div className="pageContentColumn launchmode2MarginTop14Px">
                            <div className="launchmode2InputTitle">{curLang.enter4DigitalOtp}</div>
                            <div className="launchmode2InputOtp launchmode2MarginTop10Px">
                                <input
                                    className="launchmode2Input"
                                    name="code"
                                    placeholder={curLang.enter}
                                    type="number"
                                    value={form.values.code}
                                    onBlur={form.handleBlur}
                                    onChange={form.handleChange}
                                    autoComplete="off" />
                                <div className="launchmode2InputEdge"></div>
                                {!isOtpCutdown && <div className="launchmode2SentOtpOn" onClick={() => { onHandleSendCode() }}>{curOtpText}</div>}
                                {isOtpCutdown && <div className="launchmode2SentOtpOff" onClick={() => { }}>{curOtpText}</div>}
                            </div>
                            {form.errors.code && form.touched.code && (
                                <div className="launchmode2Validate">{form.errors.code}</div>
                            )}
                        </div>
                    </form>
                </div>

                {/* 跳转应用市场 */}
                <div className="launchmode2RowGlobalPadding launchmode2FlexCenter launchmode2MarginTop42Px">
                    <div className="launchmode2BtnInstall" onClick={form.handleSubmit}>
                        <div className="launchmode2InstallText">{curLang.signUp}</div>
                    </div>
                </div>

                {/* 底部标签 */}
                <div className="launchmode2Space11Px launchmode2MarginTop42Px"></div>

            </div>}

            {!curLang && <div className="launchmode2LogoBg">
                <img className="launchmode2Logo" alt="" src={icon_app_logo} />
            </div>}

            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="launchmode2OverlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div>
    )
}